package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.Calendar;

public  class AlarmService extends AppCompatActivity implements TimePicker.OnTimeChangedListener {

    public  static final String ACTION_ALARM = "com.bok.action.btn_set";
    private AlarmManager am =null;
    private TimePicker timePicker;
    private int myhourOfDay = 0;
    private int myminute = 0;
    String text;
    private Calendar calendar = Calendar.getInstance();
    PendingIntent sender;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_service);
        timePicker = super.findViewById(R.id.tp_time);
        timePicker.setIs24HourView(true);
        timePicker.setOnTimeChangedListener(this);
        Intent i = new Intent();
        i.setAction(ACTION_ALARM);
        sender = PendingIntent.getBroadcast(AlarmService.this,0,i,PendingIntent.FLAG_CANCEL_CURRENT);
        myhourOfDay = timePicker.getCurrentHour();
        myminute = timePicker.getCurrentMinute();
        registerBroadCastReceiver();
    }

    private void registerBroadCastReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_ALARM);
        AlarmReceiver AlarmReceiver= new AlarmReceiver();
        registerReceiver(AlarmReceiver,filter);
        //注册
    }
    public void ClickSet(View view) {
        am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),sender);
        Toast.makeText(AlarmService.this,"设置成功",Toast.LENGTH_LONG).show();
        Log.d("Xsh","clickSet" + calendar.getTime());
    }

    @Override
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY,hourOfDay);
        calendar.set(Calendar.MINUTE,minute);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        myhourOfDay = hourOfDay;
        myminute = minute;
        Log.d("Xsh","onTimeChanged" + myminute + " " + myhourOfDay);
    }

    public void ClickDel(View view) {
        if (am != null){
            am.cancel(sender);
            am = null;
            text = "闹钟删除成功";
            Toast.makeText(AlarmService.this,text,Toast.LENGTH_LONG).show();
        }else {
            text = "您未设置闹钟服务";
            Toast.makeText(AlarmService.this,text,Toast.LENGTH_LONG).show();
        }
    }
}
